package com.shuai.jit.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JWT 的工具类
 */
@Component
@Slf4j
public class JwtUtil {


    private long tokenExpiration = 24*60*60*1000;
    private long refreshTime= 24*60*60*1000*3;
    private String tokenSignKey = "123456";

 
    /**
     * 校验token是否正确, 是在
     *
     * @param token
     * @return
     */
    public  boolean verify(String token) {

        Algorithm algorithm = Algorithm.HMAC256(tokenSignKey);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        try {
            verifier.verify(token);
            return true;
        }catch (Exception e){
            log.info("token 验证失败");
            return false;
        }

    }


    /**
     * 获得Token中的信息无需secret解密也能获得
     * @param token
     * @param claim
     * @return
     */
    public  String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
 
    /**
     * 生成签名,生成签名的同时，就需要重新设置 refreshtoken 的信息
     * @param account 用户名
     * @return
     */
    public String sign(String account) {

        // 帐号加JWT私钥加密
        // 此处过期时间，单位：毫秒,设置token 的过期时间
        Date date = new Date(System.currentTimeMillis() + tokenExpiration);

        Algorithm algorithm = Algorithm.HMAC256(tokenSignKey);

        // 设置 refreshtoken 过期时间
        long now_refreshTime=System.currentTimeMillis() + refreshTime;

        // 设置RefreshToken中的时间戳为当前最新时间戳
//        RedisTemplate redisTemplate= RedisUtil.get();
//        redisTemplate.opsForValue().set(JwtProperties.PREFIX_REDIS_REFRESH_TOKEN +account,refreshtime, JwtProperties.refreshTokenExpireTime, TimeUnit.MINUTES);
        return JWT.create()
                .withClaim("username", account)
                .withClaim("refreshTime",now_refreshTime )
                .withExpiresAt(date)
                .sign(algorithm);
    }
}